package com.lyt.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyt.common.QueryPageParam;
import com.lyt.common.Result;
import com.lyt.entity.Menu;
import com.lyt.entity.User;
import com.lyt.service.EmailService;
import com.lyt.service.MenuService;
import com.lyt.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private EmailService emailService;

    //日志打印
    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

    //存储验证码
    private static final Map<String, LocalDateTime> map = new HashMap<>();

    @GetMapping("/list")
    public List<User> list(){
        return userService.list();
    }
    @GetMapping("/findByNo")
    public Result findByNo(@RequestParam String no){
        List list = userService.lambdaQuery().eq(User::getNo,no).list();
        return list.size()>0?Result.suc(list):Result.fail();
    }
    //新增
    @PostMapping("/save")
    public Result save(@RequestBody User user){
        return userService.save(user)?Result.suc():Result.fail();
    }
    //更新
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        return userService.updateById(user)?Result.suc():Result.fail();
    }
    //删除
    @GetMapping("/del")
    public Result del(@RequestParam String id){
        return userService.removeById(id)?Result.suc():Result.fail();
    }

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        List list = userService.lambdaQuery()
                .eq(User::getNo,user.getNo())
                .eq(User::getPassword,user.getPassword()).list();


        if(list.size()>0){
            User user1 = (User)list.get(0);
            List menuList = menuService.lambdaQuery().like(Menu::getMenuright,user1.getRoleId()).list();
            HashMap res = new HashMap();
            res.put("user",user1);
            res.put("menu",menuList);
            return Result.suc(res);
        }
        return Result.fail();
    }

    //注册验证
    @PostMapping("/registry")
    public Result registry(@RequestBody User user){
        //如果数据出现重复，那么就表示该账号已经注册了。
        List<User> list = userService.lambdaQuery().or( wrapper -> wrapper
                        .eq(User::getNo,user.getNo())
                        .or()
                        .eq(User::getName,user.getName())
                        .or()
                        .eq(User::getPhone,user.getPhone())
                        .or()
                        .eq(User::getEmail,user.getEmail())
                )
                .list();
        if (!list.isEmpty()){
            LOG.info("该账号已经注册，请重新更换");
            return Result.fail();
        }
        LOG.info("账号创建成功");
        userService.save(user);
        return Result.suc();
    }

    //修改
    @PostMapping("/mod")
    public boolean mod(@RequestBody User user){
        return userService.updateById(user);
    }
    //新增或修改
    @PostMapping("/saveOrMod")
    public boolean saveOrMod(@RequestBody User user){
        return userService.saveOrUpdate(user);
    }
    //删除
    @GetMapping("/delete")
    public boolean delete(Integer id){
        return userService.removeById(id);
    }

    //查询（模糊、匹配）
    @PostMapping("/listP")
    public Result listP(@RequestBody User user){
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(user.getName())){
            lambdaQueryWrapper.like(User::getName,user.getName());
        }

        return Result.suc(userService.list(lambdaQueryWrapper));
    }

    @PostMapping("/listPage")
//    public List<User> listPage(@RequestBody HashMap map){
    public List<User> listPage(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        System.out.println("name==="+(String)param.get("name"));
        /*System.out.println("no==="+(String)param.get("no"));*/
        /*LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(User::getName,user.getName());

        return userService.list(lambdaQueryWrapper);*/

        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName,name);


        IPage result = userService.page(page,lambdaQueryWrapper);

        System.out.println("total=="+result.getTotal());

        return result.getRecords();
    }

    @PostMapping("/listPageC")
    public List<User> listPageC(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        System.out.println("name==="+(String)param.get("name"));



        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName,name);


        //IPage result = userService.pageC(page);
        IPage result = userService.pageCC(page,lambdaQueryWrapper);

        System.out.println("total=="+result.getTotal());

        return result.getRecords();
    }

    @PostMapping("/listPageC1")
    public Result listPageC1(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        String sex = (String)param.get("sex");
        String roleId = (String)param.get("roleId");

        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(name) && !"null".equals(name)){
            lambdaQueryWrapper.like(User::getName,name);
        }
        if(StringUtils.isNotBlank(sex)){
            lambdaQueryWrapper.eq(User::getSex,sex);
        }
        if(StringUtils.isNotBlank(roleId)){
            lambdaQueryWrapper.eq(User::getRoleId,roleId);
        }

        //IPage result = userService.pageC(page);
        IPage result = userService.pageCC(page,lambdaQueryWrapper);

        System.out.println("total=="+result.getTotal());

        return Result.suc(result.getRecords(),result.getTotal());
    }
    //找回密码的邮箱判定
    @PostMapping("/isEmail")
    public Result isEmailAndUserName(@RequestBody User user){
        if (user.getEmail().isEmpty() || user.getName().isEmpty()) {
            return Result.fail();
        }
        List<User> users = userService.lambdaQuery()
                .eq(User::getEmail,user.getEmail())
                .eq(User::getName,user.getName())
                .list();
        if (users.isEmpty()) {
            return Result.fail();
        }
        int randomCode = (int)(Math.random() * 900000) + 100000;
        emailService.sendSimpleMail(user.getEmail(), "忘记密码","您的验证码为" + randomCode + "，验证码有效时间为5分钟，如不是您本人操作，请联系管理员处理。");
        LocalDateTime localDateTime = LocalDateTime.now();
        map.put(String.valueOf(randomCode),localDateTime);
        return Result.suc(users,1L);
    }

    //判断验证码是否正确或者已经过期
    @PostMapping("/captcha")
    public Result isCaptcha(@RequestParam String captcha){
//        LOG.info(map.toString());
//        LOG.info(captcha);
        LocalDateTime startTime = map.get(captcha);
//        LOG.info(String.valueOf(startTime));
        if (startTime == null) {
            LOG.info("验证码不存在");
            return Result.fail();
        }
        LocalDateTime endTime = LocalDateTime.now();
        Duration duration = Duration.between(startTime,endTime);
        long betweenTime = duration.getSeconds();
        if (betweenTime > 300) {
            LOG.info("验证码已经过期");
            return Result.fail();
        }
        return Result.suc();
    }

    //忘记密码后再设置新密码
    @PostMapping("/setPassWord")
    public Result setPassWord(@RequestBody User user){
        List<User> users = userService.lambdaQuery()
                .eq(User::getId,user.getId())
                .list();
        //防止前端恶意传入数据
        if (users.isEmpty()) {
            LOG.info("用户不存在");
            return Result.fail();
        }
        User existingUser = users.get(0);
        existingUser.setPassword(user.getPassword());
        userService.updateById(existingUser);
        return Result.suc();
    }

}
